package com.sw.chinesewriteboard.copybook;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sw.chinesewriteboard.config.ChineseDataConfig;
import com.sw.chinesewriteboard.config.EnglishDataConfig;
import com.sw.chinesewriteboard.databinding.ActivityCopybookEnBinding;
import com.sw.chinesewriteboard.model.EnglishData;
import com.sw.chinesewriteboard.operation.CharacterOperation;
import com.sw.chinesewriteboard.operation.EnglishDataOperate;
import com.sw.chinesewriteboard.utils.BitmapUtils;
import com.sw.chinesewriteboard.utils.KeyBoardUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public abstract class EnCopyBookActivity extends CopybookActivity {

    protected ActivityCopybookEnBinding binding;

    protected int mPage = 0; // 当前页数
    private int PAGE_LENGTH = 1;    // 总页数
    private Map<String, String> mCharacterMap;  // 汉字-拼音字典
    protected LinearLayout mWordPaper;
    protected LinearLayout mWordList;
    protected EnglishDataOperate mEnglishDataOperate;
    protected int WRC = ViewGroup.LayoutParams.WRAP_CONTENT;

    protected EnglishData mData;
    protected List<String> mListContent = new ArrayList<>();

    protected Bitmap resultBitmap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityCopybookEnBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        init();
        initOwnView();
        refreshCopyBookView();
    }

    protected abstract void initOwnView();

    public EnglishData getData() {
        return mData;
    }

    public List<String> getListContent() {
        return mListContent;
    }


    protected Bitmap loadBitmapFromView() {
        int w = ChineseDataConfig.getA4width(this);
        int h = ChineseDataConfig.getA4height(this);
        System.out.println("GGGG" + w);
        System.out.println("GGGG" + h);
        System.out.println("GGGG" + mWordList.getMeasuredWidth());
        System.out.println("GGGG" + mWordList.getMeasuredHeight());

        int mainPageWidth = binding.cbIvCopybook.getWidth();
        int mainPageHeight = binding.cbIvCopybook.getHeight();

        float scaleWidth = (float) mainPageWidth / w;
        float scaleHeight = (float) mainPageHeight / h;

        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);

        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        resultBitmap = bmp;
        Canvas c = new Canvas(bmp);

        c.drawColor(Color.WHITE);
        /* 如果不设置canvas画布为白色，则生成透明 */
        mWordPaper.layout(0, 0, w, h);
        mWordPaper.draw(c);
        Bitmap resBmp = Bitmap.createBitmap(bmp, 0, 0, w, h, matrix, true);

        return resBmp;
    }

    /*
   加载其它部分
    */
    protected CharacterOperation mCharacterOperation;
    protected List<TextView> mEditTextList;

    private void init() {
        mEditTextList = new ArrayList<>();
        mCharacterOperation = new CharacterOperation(this);
        mCharacterMap = new HashMap<>();
        mData = new EnglishData(this);
        mEnglishDataOperate = new EnglishDataOperate(this);


        binding.cbIvSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveCopyBook();
            }
        });

        binding.cbIvCopybook.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.vbnBottomNavigation.setContainerInvisible();
                KeyBoardUtils.hideKeyBoard(EnCopyBookActivity.this);
            }
        });

        binding.cbIvCopybook.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });

        GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.OnGestureListener() {
            @Override
            public boolean onDown(MotionEvent e) {
                return false;
            }

            @Override
            public void onShowPress(MotionEvent e) {

            }

            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                return false;
            }

            @Override
            public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
                return false;
            }

            @Override
            public void onLongPress(MotionEvent e) {

            }

            @Override
            public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
                return false;
            }
        });
    }

    private void saveCopyBook() {
        if (resultBitmap != null) {
            showLoadingDialog();
            if(!BitmapUtils.bitmap2Path(this, resultBitmap, SAVEDIR, picName)){
                hideLoadingDialog();
                toastUtils.show("图片保存失败~");
            } else{
                binding.vbnBottomNavigation.postDelayed(() -> {
                    hideLoadingDialog();
                    toastUtils.show("图片已成功保存到相册~");
                }, 1000);
            }
        } else {
            toastUtils.show("请先编辑字帖~");
        }
    }


    protected void refreshCopyBookView() {

        int COLUMN_LENGTH = EnglishDataConfig.TOTAL_LENGTH_COLUMN;
        int ROW_LENGTH = EnglishDataConfig.TOTAL_LENGTH_ROW;

        mWordPaper = new LinearLayout(this);
        mWordPaper.setLayoutParams(new LinearLayout.LayoutParams(ChineseDataConfig.getA4width(this), ChineseDataConfig.getA4height(this)));
        mWordPaper.setGravity(Gravity.CENTER);
        mWordPaper.setAlpha(0f);
        binding.getRoot().addView(mWordPaper);

        mWordList = new LinearLayout(this);
        mWordList.setLayoutParams(new LinearLayout.LayoutParams(WRC, WRC));
        mWordList.setOrientation(LinearLayout.VERTICAL);
        mWordList.removeAllViews();

        mEditTextList.clear();


        mData.setText(mEnglishDataOperate.listToString(mListContent));

        int startIndex = EnglishDataConfig.TOTAL_LENGTH * mPage;    // 字符串的起始坐标
        int k = startIndex;
        System.out.println("日志：p：" + mPage + "    k:" + k);
        for (int i = 0; i < ROW_LENGTH; i++) {
            LinearLayout row = new LinearLayout(this);
            row.setLayoutParams(new LinearLayout.LayoutParams(WRC, WRC));
            row.setOrientation(LinearLayout.HORIZONTAL);
            for (int j = 0; j < COLUMN_LENGTH; j++) {
                View view = createCharacterLayout(mData.getText().charAt(k), mData);
                view.setLayoutParams(new LinearLayout.LayoutParams(WRC, WRC));
                row.addView(view);
                k++;
            }
            mWordList.addView(row);
        }
        mWordPaper.addView(mWordList);

        binding.cbIvCopybook.post(new Runnable() {
            @Override
            public void run() {
                resultBitmap = loadBitmapFromView();
                binding.cbIvCopybook.setImageBitmap(resultBitmap);
                binding.getRoot().removeView(mWordPaper);
            }
        });
    }

    @SuppressLint("SetTextI18n")
    protected View createCharacterLayout(char c, EnglishData data) {
        int gridWidth = EnglishDataConfig.getGridWidth(EnCopyBookActivity.this);
        int gridHeight = EnglishDataConfig.getGridHeight(EnCopyBookActivity.this);

        LinearLayout characterLayout = new LinearLayout(this);
        characterLayout.setLayoutParams(new LinearLayout.LayoutParams(WRC, WRC));
        characterLayout.setOrientation(LinearLayout.VERTICAL);

        final TextView character = new TextView(this);

        character.setGravity(Gravity.CENTER);
        LinearLayout.LayoutParams characterParams = new LinearLayout.LayoutParams(gridWidth, gridHeight);
        characterParams.bottomMargin = gridHeight;
        character.setEnabled(false);
        character.setText("" + c);
        mCharacterOperation.setCharacterAppearance(character, data);
        mEditTextList.add(character);
        characterLayout.addView(character, characterParams);

        return characterLayout;
    }
}
